//
//  OrderDetailsVC.m
//  ProjectforHDX
//
//  Created by wusiping on 16/9/5.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "OrderDetailsVC.h"
//#import "LocalRepairOrderCell.h"
#import "OrderDetailsHeadView.h"
#import "BottomOperationView.h"
#import "LCOrderDetailCell.h"


//修改
#import "CSNewOrderLCVC.h"
#import "CSNewOrderServiceVC.h"
#import "CSNewOrderManageVC.h"
#import "CSNewOrderReplaceVC.h"

//安排发货
#import "DeliveryPartReplaceVC.h"
#import "CSSettleDeliveryUpdatePlateTVC.h"

//查看物流
#import "CMyOrderCenterDetailCheck.h"
#import "DeliverModel.h"



@interface OrderDetailsVC ()<UITableViewDataSource,UITableViewDelegate>{
    UIView *bottomView;
   
}

@property (nonatomic, strong)UITableView *tableView;

/**
 *  订单详情总字典
 */
@property (nonatomic, strong)NSMutableDictionary *dataDict;

/**
 *  物流字典
 */
@property (nonatomic, strong)NSMutableDictionary *logisticsDict;


/**
 *  订单状态字典
 */
@property (nonatomic, strong)NSMutableDictionary *orderStatusDict;

/**
 *  订单类型字典
 */
@property (nonatomic, strong)NSMutableDictionary *orderTypeInfoDict;


/**
 *  板件信息字典，里面是板件数组
 */
@property (nonatomic, strong)NSMutableDictionary *platesInfoDict;


/**
 *  板件数组
 */
@property (nonatomic, strong)NSMutableArray *platesArray;


/**
 *  收获联系人信息
 */
@property (nonatomic, strong)NSMutableDictionary *receiverInfoDict;

/**
 *  备注
 */
@property (nonatomic, strong)NSString *remark;

/**
 *  1准时送达  2延时送达
 */
@property (nonatomic, strong)NSString *arriveStatus;


@end

@implementation OrderDetailsVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];

}

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self UIConfig];
    [self getOrderDetails];
    

}

- (void)dataConfig{
    
    self.logisticsDict = [[NSMutableDictionary alloc]init];
    self.orderStatusDict = [[NSMutableDictionary alloc]init];
    self.orderTypeInfoDict = [[NSMutableDictionary alloc]init];
    self.platesInfoDict = [[NSMutableDictionary alloc]init];
    self.platesArray = [[NSMutableArray alloc]init];
    self.receiverInfoDict = [[NSMutableDictionary alloc]init];
    self.remark = @"";
    
    self.orderStatusDict = [self.dataDict objectForKey:@"orderStatus"];
    self.receiverInfoDict = [self.dataDict objectForKey:@"receiverInfo"];
    self.logisticsDict = [self.dataDict objectForKey:@"logistics"];
    self.orderTypeInfoDict = [self.dataDict objectForKey:@"orderTypeInfo"];
    self.remark = [self.dataDict objectForKey:@"remark"];
    self.platesInfoDict = [self.dataDict objectForKey:@"platesInfo"];
    self.platesArray = [self.platesInfoDict objectForKey:@"plates"];
    [self setupBottomView];

}

- (void)UIConfig{
    
    
    self.labnav.text = [UtilCheck language:@"order.detail"];
    self.labnav.textColor = [UIColor whiteColor];
    self.labnav.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0  ,self.view.width , self.view.height - 64 - 52)];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LocalRepairOrderCell" bundle:nil] forCellReuseIdentifier:@"LocalRepairOrderCell"];

}

- (void)setupBottomView{
    OrderDetailsHeadView *headView = [[OrderDetailsHeadView alloc]initHeaderViewWithOrderStatusDic: self.orderStatusDict  AndReceiverDict:self.receiverInfoDict AndlogisticsDict:self.logisticsDict AndOrderTypeInfoDict:self.orderTypeInfoDict];
    self.tableView.tableHeaderView = headView;
    
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.width, 35)];
    RZCustomLable *remarkLab = [[RZCustomLable alloc]init];
    [remarkLab setFrame:CGRectMake(16, 7.5, self.tableView.width, 20)];
    [remarkLab setText:[NSString stringWithFormat: @"%@:%@",[THMangerTool language:@"order.remark"],self.remark]];
    remarkLab.numberOfLines = 0;
    [footView addSubview:remarkLab];
    self.tableView.tableFooterView = footView;
    
    NSArray *arr= [[self.orderStatusDict objectForKey:@"operation"] componentsSeparatedByString:@","];
    if (arr.count == 0) {
        return;
    }else if (arr.count == 1){
        if ([arr[0] isKindOfClass:[NSString class]]) {
            if ([arr[0] length] <= 0) {
                return;
            }
        }else{
            return;
        }
    }
    //    1取消订单2修改订单，3安排发货，4确认订单，5继续发货，6确认收货，7查看物流
    BottomOperationView *footView2 = [[BottomOperationView alloc]initWithOperationArray:arr AndOperationType:@"order" btnClick:^(long tag) {
        [self btnClick:tag];
    }];
    
    [self.view addSubview:footView2];
    [footView2 setFrame:CGRectMake(0, self.tableView.bottom, self.view.width, 52)];

}

#pragma mark tableview delegate



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSLog(@"cell的个数是:%ld",self.platesArray.count);
    return self.platesArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    LCOrderDetailCell *   cell  = [[LCOrderDetailCell alloc]init];
    
    NSMutableDictionary *dict =  [[NSMutableDictionary alloc]initWithDictionary:self.platesArray[indexPath.row]];
    [cell setDataDict: dict];

    cell.type = [self.orderStatusDict objectForKey:@"type"];
    cell.needNum = YES;
    if (indexPath.row != 0) {
        cell.needNum = NO;
    }
    cell.indexLab.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
 

    return [cell getHeightWithDict:dict];
    
    
}



-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LCOrderDetailCell *   cell = (LCOrderDetailCell*)[tableView dequeueReusableCellWithIdentifier:@"LCOrderDetailCell"];
    
    if(cell == nil)
    {
        cell = [[LCOrderDetailCell alloc] init];
    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:self.platesArray[indexPath.row]];
    
    cell.type = [self.orderTypeInfoDict objectForKey:@"orderType"];
    [cell setDataDict: dict];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.needNum = YES;
    if (indexPath.row != 0) {
        cell.needNum = NO;
    }
    
    cell.indexLab.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    cell.repairNumLab.text = [NSString stringWithFormat:@"%@:%ld",[THMangerTool language:@"order.unit"],self.platesArray.count];
  
    return cell;
    
}

#pragma mark  底部按钮点击
/**
 *  按钮点击
 *sender.tag 1取消订单2修改订单，3安排发货，4确认订单，5继续发货，6确认收货，7查看物流
 *  @param sender
 */
-(void)btnClick:(long)sender{
    
    THUserInfoModel *userModel=[THMangerTool getAccountInfo];
    
    switch (sender) {
        case 1://取消订单
        {
            [self cancelOrderDetails];
        }
            break;
        case 2://修改订单
        {
            
            if ([userModel.userType integerValue] == 1) {//客户
                if ([[self.orderStatusDict objectForKey:@"type"] integerValue] == 1){
                    CSNewOrderManageVC *vc = [[CSNewOrderManageVC alloc]init];
                    vc.dict = self.dataDict;
                    vc.order = 1;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    CSNewOrderReplaceVC *vc = [[CSNewOrderReplaceVC alloc]init];
                    vc.dict = self.dataDict;
                    vc.order = 1;
                    [self.navigationController pushViewController:vc animated:YES];   // 数据完成
                }
                
            }else if ([userModel.userType integerValue] == 2) {//客服
                if ([[self.orderStatusDict objectForKey:@"type"] integerValue] == 1) {//备件管理服务
                    CSNewOrderLCVC *vc = [[CSNewOrderLCVC alloc]init];
                    vc.dict = self.dataDict;
                    vc.order = 1;
                    [self.navigationController pushViewController:vc animated:YES];    //数据完成
                }else{
                    CSNewOrderServiceVC *vc = [[CSNewOrderServiceVC alloc]init];
                    vc.dict = self.dataDict;
                    vc.order = 1;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else {// 仓管
                NSLog(@"进入修改时，状态不对");
            }
            
        }
            break;
        case 3://安排发货
        {
            //            CSSettleDeliveryUpdatePlateTVC *view = [[CSSettleDeliveryUpdatePlateTVC alloc]init];
            //                            view.orderCode = self.orderCode;
            //                            [self.navigationController pushViewController:view animated:YES];
            
            
            if ([userModel.userType integerValue] == 2) {//客服
                CSSettleDeliveryUpdatePlateTVC *view = [[CSSettleDeliveryUpdatePlateTVC alloc]init];
                view.orderCode = self.orderCode;
                [self.navigationController pushViewController:view animated:YES];
                
            }else{
                DeliveryPartReplaceVC *vc = [[DeliveryPartReplaceVC alloc]init];
                vc.orderCode = self.orderCode;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
            break;
        case 4://确认订单
        {
            [self confirmOrderDetails];
        }
            break;
        case 5:
        {
            if ([userModel.userType integerValue] == 2) {//客服
                CSSettleDeliveryUpdatePlateTVC *view = [[CSSettleDeliveryUpdatePlateTVC alloc]init];
                view.orderCode = self.orderCode;
                [self.navigationController pushViewController:view animated:YES];
                
            }else{
                DeliveryPartReplaceVC *vc = [[DeliveryPartReplaceVC alloc]init];
                vc.orderCode = self.orderCode;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
            break;
        case 6://确认收货
        {
            bottomView = [[UIView alloc]init];
            [bottomView setFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
            [bottomView setBackgroundColor:[UIColor colorWithWhite:0.f alpha:0.5 ]];
            [self.view addSubview:bottomView];
            
            UIView *alertView = [[UIView alloc]init];
            [alertView setFrame:CGRectMake((self.view.width-280)/2, (self.view.height-150)/2, 280, 150)];
            [alertView setBackgroundColor:[UIColor whiteColor]];
            [alertView.layer setCornerRadius:20];
            [alertView.layer setMasksToBounds:YES];
            [bottomView addSubview:alertView];
            
            UILabel *Line = [[UILabel alloc]init];
            [Line setBackgroundColor:[UtilCheck hexStringToColor:@"e8e8e8" alpha:1]];
            [Line setFrame:CGRectMake(0, 150-44, 280, 0.5)];
            [alertView addSubview:Line];
            UILabel *verticalLine = [[UILabel alloc]init];
            [verticalLine setBackgroundColor:[UtilCheck hexStringToColor:@"e8e8e8" alpha:1]];
            [verticalLine setFrame:CGRectMake(280/2, 150-44, 0.5, 44)];
            [alertView addSubview:verticalLine];
            
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, alertView.width, 60)];
            title.textAlignment = UITextAlignmentCenter;
            [title setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
            title.text = [THMangerTool language:@"show.WarmTip"];
            [alertView addSubview:title];
            UILabel *message = [[UILabel alloc]initWithFrame:CGRectMake(0, title.height-25, alertView.width, 60)];
            message.textAlignment = UITextAlignmentCenter;
            [message setFont:[UIFont systemFontOfSize:18]];
            message.text = [THMangerTool language:@"CSMyOrderConfirmingTVC.DeliveredOnTime"];
            [alertView addSubview:message];
            
            UIButton *cancelButtonTitle = [UIButton buttonWithType:(UIButtonTypeCustom)];
            [cancelButtonTitle setFrame:CGRectMake(0, Line.bottom, alertView.width/2, 44)];
            [cancelButtonTitle setTitle:[THMangerTool language:@"CSMyOrderConfirmingTVC.OnTime"] forState:(UIControlStateNormal)];
            [cancelButtonTitle setTitleColor:[UtilCheck hexStringToColor:@"1CB0F6" alpha:1] forState:(UIControlStateNormal)];
            [cancelButtonTitle addTarget:self action:@selector(cancelButtonTitle) forControlEvents:(UIControlEventTouchUpInside)];
            [alertView addSubview:cancelButtonTitle];
            UIButton *otherButtonTitles = [UIButton buttonWithType:(UIButtonTypeCustom)];
            [otherButtonTitles setFrame:CGRectMake(cancelButtonTitle.right, Line.bottom, alertView.width/2, 44)];
            [otherButtonTitles setTitle:[THMangerTool language:@"CSMyOrderConfirmingTVC.Delayed"] forState:(UIControlStateNormal)];
            [otherButtonTitles setTitleColor:[UtilCheck hexStringToColor:@"1CB0F6" alpha:1] forState:(UIControlStateNormal)];
            [otherButtonTitles addTarget:self action:@selector(otherButtonTitles) forControlEvents:(UIControlEventTouchUpInside)];
            [alertView addSubview:otherButtonTitles];
            
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:[UtilCheck language:@"show.WarmTip"] message:[UtilCheck language:@"CSMyOrderConfirmingTVC.DeliveredOnTime"] preferredStyle:UIAlertControllerStyleAlert];
//            [self presentViewController:alert animated:YES completion:nil];
//            [alert addAction:[UIAlertAction actionWithTitle:[UtilCheck language:@"CSMyOrderConfirmingTVC.OnTime"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                self.arriveStatus = @"1";
//                [self confirmReceive];
//                
//            }]];
//            
//            [alert addAction:[UIAlertAction actionWithTitle:[UtilCheck language:@"show.delay"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                self.arriveStatus = @"2";
//                [self confirmReceive];
//                
//            }]];
           
        }
            break;
        case 7://查看物流
        {
            
            DeliverModel *model = [[DeliverModel alloc]init];
            model.com =  self.logisticsDict[@"logisticsInfo"][@"com"];
            model.code = self.logisticsDict[@"logisticsInfo"][@"code"];
            if ([model.com isEqualToString:@"其他"]||[model.com isEqualToString:@"other"]) {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.noCom"]];
            }
            else {
                CMyOrderCenterDetailCheck *vc = [[CMyOrderCenterDetailCheck alloc]init];
                [vc setDeliver:model];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
            
        case 9://发货
        {
            if ([userModel.userType integerValue] == 2) {//客服
                CSSettleDeliveryUpdatePlateTVC *view = [[CSSettleDeliveryUpdatePlateTVC alloc]init];
                view.orderCode = self.orderCode;
                [self.navigationController pushViewController:view animated:YES];
                
            }else{
                DeliveryPartReplaceVC *vc = [[DeliveryPartReplaceVC alloc]init];
                vc.orderCode = self.orderCode;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
            
            
        default:
            break;
    }
}


#pragma mark 网络请求
/**
 *  获取订单详情
 */
- (void)getOrderDetails {
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"]=self.orderCode;
    [AFHttpTool postJsonDatawithUrl:@"LCOrderDetail"  parameters:[params mutableCopy] success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] ) {
            self.dataDict = [[NSMutableDictionary alloc]initWithDictionary: [responseObject objectForKey:@"data"]];
            
            [self dataConfig];

            NSLog(@"订单详情数据%@",self.dataDict);
            
            if (self.dataDict != nil) {
                [self dataConfig];
                [self setupBottomView];
                [self.tableView reloadData];
            }
            else {
                self.tableView.tableHeaderView = nil;
                [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView  top:30 title:[THMangerTool language:@"HUD.noOrderData"]  onClick:nil];
            }
        }
        else {
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
        
    }];
}

/**
 *  取消订单
 */
- (void)cancelOrderDetails {
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"]=self.orderCode;
    [AFHttpTool postJsonDatawithUrl:@"cancelOrder"  parameters:[params mutableCopy] success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] ) {
            
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else {
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
        
    }];
}


/**
 *  确认订单
 */
- (void)confirmOrderDetails {
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"]=self.orderCode;
    [AFHttpTool postJsonDatawithUrl:@"confirmOrder"  parameters:[params mutableCopy] success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] ) {
            
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            [self getOrderDetails];
            [self.tableView reloadData];
            
        }
        else {
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
        
    }];
}

/**
 *  确认收货
 */
- (void)confirmReceive {
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"]=self.orderCode;
    
    if (self.arriveStatus == nil) {
        [Toolobject showAlterwithMessage:@"请选择送达状态"];
    }
    [params setValue:self.arriveStatus forKey:@"result"];
    [AFHttpTool postJsonDatawithUrl:@"confirmReceive"  parameters:[params mutableCopy] success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] ) {
            
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            [self getOrderDetails];
            [self.tableView reloadData];
            
            
        }
        else {
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
        
    }];
    
}

#pragma mark 弹框点击事件
- (void)cancelButtonTitle {
    [bottomView removeFromSuperview];
    self.arriveStatus = @"1";
    [self confirmReceive];
}
- (void)otherButtonTitles {
    [bottomView removeFromSuperview];
    self.arriveStatus = @"2";
    [self confirmReceive];
}















@end
